﻿using System;
using System.Collections.Specialized;
using System.Text;
using Microsoft.SharePoint;
using MSPE.Public.FOSS.AutoStatusPlus.Common;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.OperationHelpers;
using MSPE.Public.FOSS.AutoStatusPlus.StsAdm.SPValidators;

namespace MSPE.Public.FOSS.AutoStatusPlus.StsAdm.Commands
{
    class AspLogUpdates : SPOperation
    {
        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="AspLogUpdates"/> class.
        /// </summary>
        public AspLogUpdates()
        {
            SPParamCollection _parameters = new SPParamCollection
                                                {
                                                    new SPParam(GlobalConstants.UrlParamName, GlobalConstants.UrlParamName, true, null,
                                                                new SPUrlValidator(), "Please specify the PWA site URL."),
                                                    new SPParam(GlobalConstants.OffParamName, GlobalConstants.OffParamName)
                                               };

            StringBuilder _sb = new StringBuilder();
            _sb.AppendLine("-url <URL of PWA Site>");
            _sb.AppendLine("\t[-off]");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("\tThis command controls whether AutoStatusPlus will write to a");
            _sb.AppendLine("\tdetailed log file stored on the local disk when it's");
            _sb.AppendLine("\tprocessing status updates.");
            _sb.AppendLine();
            _sb.AppendLine("\tTo configure the settings for this log file, including its");
            _sb.AppendLine("\tlocation, prefix, and lifetime, please see the");
            _sb.AppendLine("\thelp for the AspSetLogOptions command.");
            _sb.AppendLine();
            _sb.AppendLine();
            _sb.AppendLine("\tThe default setting is on.");

            Init(_parameters, _sb.ToString());
        }
        #endregion // Constructors

        #region Methods
        #region Overrides
        public override int Execute(string command, StringDictionary keyValues, out string output)
        {
            throw new NotImplementedException();
        } // Execute()

        /// <summary>
        /// Gets the help message.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        public override string GetHelpMessage(string command)
        {
            return HelpMessage;
        } // GetHelpMessage()

        /// <summary>
        /// Runs the specified command.
        /// </summary>
        /// <param name="command">The command.</param>
        /// <param name="keyValues">The key values.</param>
        /// <param name="output">The output.</param>
        /// <returns></returns>
        public override int Run(string command, StringDictionary keyValues, out string output)
        {
            SPSite _site = null;
            SPWeb _pwaWeb = null;

            try
            {
                #region Read configuration settings from command line
                output = string.Empty;

                InitParameters(keyValues);

                // Read params into local fields
                string _url = Params[GlobalConstants.UrlParamName].Value.TrimEnd('/');
                #endregion // Read configuration settings from command line

                // Get the PWA site
                _site = new SPSite(_url);

                if (_site.Url != _url)
                    throw new Exception("You may only configure Project Web Access Sites.");

                _pwaWeb = _site.RootWeb;

                if (_pwaWeb == null)
                    throw new Exception("Could not load the Site at the specified URL.");

                if (_pwaWeb.WebTemplateId != GlobalConstants.PwaSiteTemplateId)
                    throw new Exception("You may only configure Project Web Access Sites.");

                // Load current settings
                Settings _loadedSettings = Settings.LoadSettings(_pwaWeb);

                // Update setting
                _loadedSettings.LogUpdates = !Params[GlobalConstants.OffParamName].UserTypedIn;
                Settings.UpdateSettings(_pwaWeb, _loadedSettings);

                // Use the ErrorCodes enum to return error codes: 
                // ErrorCodes.SyntaxError
                // ErrorCodes.GeneralError

                // Return 0 for success.
                return 0;
            } // End try

            catch (Exception ex)
            {
                throw new Exception("Error encountered while configuring site:\n\n" + ex.ToString());
            } // End catch

            finally
            {
                if (_pwaWeb != null) _pwaWeb.Dispose();
                if (_site != null) _site.Dispose();
            } // End finally
        } // Run()
        #endregion // Overrides
        #endregion // Methods
    }
}
